package cn.js.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.js.domain.UserVo;
import jakarta.servlet.http.HttpServletResponse;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/oauth")
public class RestAuthController {
    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    /**
     * 回调方法
     * @param callback
     * @return
     */

    @RequestMapping("/callback")
    public Object login(AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest();
        JSONObject jsonObject =
                JSONUtil.parseObj(authRequest.login(callback), false);
        JSONObject jsonStr = JSONUtil.parseObj(jsonObject.get("data"), false);
        UserVo userVo = new UserVo();
        userVo.setUserId(Long.parseLong(jsonStr.get("uuid").toString()));
        userVo.setUserName(jsonStr.get("username").toString());
        userVo.setNickName(jsonStr.get("nickname").toString());
        userVo.setAvatar(jsonStr.get("avatar").toString());

        //这些信息就可以保存进入到我们自己的系统中

        return userVo;
    }

    private AuthRequest getAuthRequest() {
        return  new AuthGiteeRequest(AuthConfig.builder()
                .clientId("a77b41651520b7688beabc71435470832ef6c7d8280e374a6710c0498e12bac6")
                .clientSecret("a5c02eec365c3ac15f0c00f5d35f6a9f8ea3320bfd180af2ad8c72428d2fbc7a")
                .redirectUri("http://localhost:8080/oauth/callback")
                .build());
    }
}
